<template>
  <div class="home-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6" v-for="item in statData" :key="item.type">
        <el-card shadow="hover" class="stat-card" @click="handleCardClick(item.type)">
          <div class="stat-content">
            <el-icon :size="40" :color="item.color">
              <component :is="item.icon" />
            </el-icon>
            <div class="stat-info">
              <div class="stat-title">{{ item.title }}</div>
              <div class="stat-value">{{ item.value }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表区域 - 只对管理员显示 -->
    <div v-if="isAdmin">
      <el-row :gutter="20" class="chart-row">
        <!-- 饼状图 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>违法类型分布</span>
                <div class="date-filter">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="handleExportReport" 
                    style="margin-right: 10px;"
                  >
                    <el-icon><Download /></el-icon> 导出报表
                  </el-button>
                  <el-radio-group v-model="dateType" size="small" @change="handleDateTypeChange">
                    <el-radio-button label="week">本周</el-radio-button>
                    <el-radio-button label="month">本月</el-radio-button>
                    <el-radio-button label="custom">自定义</el-radio-button>
                  </el-radio-group>
                  <el-date-picker
                    v-if="dateType === 'custom'"
                    v-model="dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    size="small"
                    :shortcuts="dateShortcuts"
                    @change="fetchData"
                    style="margin-left: 10px; width: 260px"
                  />
                </div>
              </div>
            </template>
            <div class="pie-chart-container">
              <v-chart class="chart" :option="pieChartOption" autoresize />
            </div>
          </el-card>
        </el-col>
        
        <!-- 趋势图 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>违法趋势分析</span>
              </div>
            </template>
            <div class="chart-wrapper">
              <v-chart class="chart" :option="lineChartOption" autoresize />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 普通用户的内容区域 -->
    <div v-if="!isAdmin" class="user-content">
      <el-card class="user-card">
        <template #header>
          <div class="card-header">
            <span>我的工作台</span>
          </div>
        </template>
        <div class="workspace-content">
          <p>欢迎使用交通违法识别管理系统，您可以在这里查看个人违法记录和提交申诉。</p>
          <el-button type="primary" @click="router.push('/my-violations')">查看我的违法记录</el-button>
          <el-button type="success" @click="router.push('/appeal')">管理我的申诉</el-button>
          <el-button type="warning" @click="router.push('/index')">
            <el-icon><VideoCamera /></el-icon>
            智能交通监控
          </el-button>
        </div>
      </el-card>
    </div>
    
    <!-- 管理员也添加快捷入口 -->
    <div v-if="isAdmin" class="admin-quick-actions">
      <el-card class="quick-actions-card">
        <template #header>
          <div class="card-header">
            <span>快捷操作</span>
          </div>
        </template>
        <div class="quick-actions-content">
          <el-button type="primary" @click="router.push('/violation')">
            <el-icon><List /></el-icon>
            违法记录管理
          </el-button>
          <el-button type="success" @click="router.push('/alert')">
            <el-icon><Bell /></el-icon>
            预警管理
          </el-button>
          <el-button type="warning" @click="router.push('/index')">
            <el-icon><VideoCamera /></el-icon>
            智能交通监控
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'


// 导入 getViolationPie, getViolationStatistics 和 exportViolationReport
import { getViolationPie, getViolationStatistics, exportViolationReport } from '@/api/dashboard'  // 确保路径正确
// 导入 Download 图标
import { Download, VideoCamera, List, Bell } from '@element-plus/icons-vue'

// 注册必要的组件
use([
  CanvasRenderer,
  PieChart,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 颜色映射 - 只保留实际使用的类型
const colorMap = {
  '闯红灯': '#f56c6c',
  '超速': '#e6a23c',
  '其他违法': '#67c23a',
  '总违法': '#409eff'
}

const router = useRouter()
const userStore = useUserStore()

// 将isAdmin定义为全局计算属性
const isAdmin = computed(() => {
  return userStore.userInfo?.role === '1' || userStore.userInfo?.role === '2'
})

// 日期类型：week(本周)/month(本月)/custom(自定义)
const dateType = ref('week')
const dateRange = ref([])

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    }
  }
]

// 辅助函数：格式化日期为 "yyyy-MM-dd"，与后端@DateTimeFormat(pattern = "yyyy-MM-dd")匹配
const formatDate = (date) => {
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 处理日期类型变化
const handleDateTypeChange = (type) => {
  dateType.value = type
  if (type === 'week') {
    const end = new Date()
    const start = new Date()
    start.setDate(start.getDate() - 7)
    dateRange.value = [start, end]
  } else if (type === 'month') {
    const end = new Date()
    const start = new Date()
    start.setMonth(start.getMonth() - 1)
    dateRange.value = [start, end]
  }
  fetchData()
}

// 图表数据
const pieChartData = ref([])
const lineChartData = ref({
  dates: [],
  runRedData: [],
  overSpeedData: [],
  otherData: [],
  totalData: []
})

// 饼图配置
const pieChartOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 10,
    top: 'center',
    data: pieChartData.value.map(item => item.name)
  },
  series: [
    {
      name: '违法类型',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: pieChartData.value
    }
  ]
}))

// 折线图配置
const lineChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['闯红灯', '超速', '其他违法', '总违法']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: lineChartData.value.dates
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '闯红灯',
      type: 'line',
      stack: 'Total',
      data: lineChartData.value.runRedData,
      itemStyle: {
        color: colorMap['闯红灯']
      }
    },
    {
      name: '超速',
      type: 'line',
      stack: 'Total',
      data: lineChartData.value.overSpeedData,
      itemStyle: {
        color: colorMap['超速']
      }
    },
    {
      name: '其他违法',
      type: 'line',
      stack: 'Total',
      data: lineChartData.value.otherData,
      itemStyle: {
        color: colorMap['其他违法']
      }
    },
    {
      name: '总违法',
      type: 'line',
      data: lineChartData.value.totalData,
      itemStyle: {
        color: colorMap['总违法']
      }
    }
  ]
}))

// 获取数据
const fetchData = async () => {
  if (!dateRange.value || dateRange.value.length !== 2) {
    ElMessage.warning('请选择日期范围')
    return
  }

  try {
    const begin = formatDate(dateRange.value[0])
    const end = formatDate(dateRange.value[1])
    // 从userStore获取role并转换为数字
    const role = parseInt(userStore.userInfo?.role)

    const [pieRes, lineRes] = await Promise.all([
      getViolationPie({ begin, end }, role),
      getViolationStatistics({ begin, end }, role)
    ])

    console.log('pieRes:', pieRes)
    console.log('lineRes:', lineRes)

    if (
        pieRes && pieRes.code === 200 &&
        lineRes && lineRes.code === 200
    ) {
      const pieData = pieRes.data
      const lineData = lineRes.data

      // 更新饼图数据
      pieChartData.value = [
        { name: '闯红灯', value: parseFloat(pieData.carRunRedList || 0), itemStyle: { color: colorMap['闯红灯'] } },
        { name: '超速', value: parseFloat(pieData.overSpeedList || 0), itemStyle: { color: colorMap['超速'] } },
        { name: '其他违法', value: parseFloat(pieData.touchLineList || 0) + parseFloat(pieData.turnWrongList || 0), itemStyle: { color: colorMap['其他违法'] } }
      ]

      // 更新折线图数据
      lineChartData.value = {
        dates: lineData.dateList ? lineData.dateList.split(',') : [],
        runRedData: lineData.carRunRedList ? lineData.carRunRedList.split(',').map(Number) : [],
        overSpeedData: lineData.overSpeedList ? lineData.overSpeedList.split(',').map(Number) : [],
        otherData: lineData.touchLineList ? lineData.touchLineList.split(',').map(Number) : [],
        totalData: lineData.violationList ? lineData.violationList.split(',').map(Number) : []
      }

      // 更新 statistics 数据
      statistics.value = {
        today: lineData.totalViolation || 0,
        week: lineData.totalViolation || 0,
        month: lineData.totalViolation || 0,
        alert: lineData.waitWarning || 0
      }
      userstatistics.value ={
        myviolation: lineData.totalViolation || 0,
        mywarning: pieData.waitWarning || 0
      }
      console.log(userstatistics.value)
    } else {
      ElMessage.error('获取数据失败')
      resetTrendData()
    }
  } catch (error) {
    console.error('获取数据出错:', error)
    ElMessage.error('获取数据出错')
    resetTrendData()
  }
}

// 重置趋势数据
const resetTrendData = () => {
  lineChartData.value = {
    dates: [],
    runRedData: [],
    overSpeedData: [],
    otherData: [],
    totalData: []
  };
}

// 处理导出报表
const handleExportReport = () => {
  exportViolationReport()
}

// 顶部统计卡片数据
const statData = computed(() => {
  if (isAdmin.value) {
    // 管理员看到的统计卡片
    return [
      {
        title: '今日违法数量',
        value: statistics.value.today,
        icon: 'Warning',
        color: '#f56c6c',
        type: 'today'
      },
      {
        title: '本周违法数量',
        value: statistics.value.week,
        icon: 'DataAnalysis',
        color: '#e6a23c',
        type: 'week'
      },
      {
        title: '本月违法数量',
        value: statistics.value.month,
        icon: 'Calendar',
        color: '#67c23a',
        type: 'month'
      },
      {
        title: '待处理预警',
        value: statistics.value.alert,
        icon: 'Bell',
        color: '#409eff',
        type: 'alert'
      }
    ]
  } else {
    // 普通用户看到的统计卡片
    console.log(userstatistics.value)
    return [
      {
        title: '我的违法记录',
        value: userstatistics.value.myviolation || 0,
        icon: 'Document',
        color: '#f56c6c',
        type: 'myViolations'
      },
      {
        title: '待处理申诉',
        value: userstatistics.value.mywarning || 0,
        icon: 'ChatDotRound',
        color: '#e6a23c',
        type: 'myAppeals'
      },
      {
        title: '工作台',
        value: '进入',
        icon: 'Monitor',
        color: '#67c23a',
        type: 'workspace'
      },
      {
        title: '个人中心',
        value: '查看',
        icon: 'User',
        color: '#409eff',
        type: 'profile'
      }
    ]
  }
})

// 处理卡片点击
const handleCardClick = (type) => {
  if (isAdmin.value) {
    // 管理员的卡片点击处理
    if (type === 'alert') {
      router.push('/alert')
    } else {
      handleDateTypeChange(type)
    }
  } else {
    // 普通用户的卡片点击处理
    switch (type) {
      case 'myViolations':
        // 跳转到个人违法记录页面（需要创建）
        router.push('/my-violations')
        break
      case 'myAppeals':
        router.push('/appeal')
        break
      case 'workspace':
        router.push('/workspace')
        break
      case 'profile':
        router.push('/profile')
        break
    }
  }
}

// 动态统计首页卡片数据
const statistics = ref({
  today: 0,
  week: 0,
  month: 0,
  alert: 0
})
const userstatistics = ref({
  myviolation: 0,
  waitappeal: 0
})

// 违法类型分布数据
const typeDistribution = ref([])

// 初始化加载数据
onMounted(() => {
  // 删除这一行，直接使用全局计算属性
  // const isAdmin = userStore.userInfo?.role === '1' || userStore.userInfo?.role === '2'
  
  // 设置默认日期范围为最近一周
  const end = new Date()
  const start = new Date()
  start.setDate(start.getDate() - 7)
  dateRange.value = [start, end]
  
  // 获取统计数据，根据用户角色决定API调用
  fetchData()
  
  if (isAdmin.value) {
    handleDateTypeChange('week') // 默认显示本周数据
  }
})
</script>

<style scoped>
.home-container {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 20px;
}

.stat-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-title {
  font-size: 14px;
  color: #909399;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-top: 5px;
}

.chart-card {
  margin-bottom: 20px;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.date-filter {
  display: flex;
  align-items: center;
}

.stat-card {
  height: 100%;
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  font-size: 48px;
  margin-right: 15px;
}

.chart-row {
  margin-top: 20px;
}

.pie-chart-container {
  height: 300px;
}

.chart-wrapper {
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

.workspace-content {
  text-align: center;
}

.workspace-content .el-button {
  margin: 0 10px 10px 0;
  min-width: 140px;
}

.admin-quick-actions {
  margin-top: 20px;
}

.quick-actions-content {
  text-align: center;
  padding: 20px;
}

.quick-actions-content .el-button {
  margin: 0 15px 10px 0;
  min-width: 140px;
}

.quick-actions-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.quick-actions-card .card-header {
  color: white;
  font-weight: bold;
}
</style>